// 分类参数的逻辑代码
export default {
  created() {
    this.getData();
  },
  data() {
    return {
      // 1准备级联数据
      selectedCateArr: [], //选中的第三集数据
      cascaderOptions: [], //所有选项
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
      },
      // 准备tab的参数
      activeName: "many",
      manyAttrs: [],
      onlyAttrs: [],
      disabled: true,
      // 添加参数的数据
      adddialogFormVisible: false,
      rules: {
        attr_name: [
          { required: true, message: "参数名称必填", trigger: "blur" }
        ]
      },
      form: {
        attr_name: ""
      },
      // 编辑参数的数据
      editdialogFormVisible: false,
      editForm: {
        attr_name: "",
        attr_id: ""
      }
    };
  },
  computed: {
    thirdCateId() {
      let id = null;
      if (this.selectedCateArr.length === 3) {
        id = this.selectedCateArr[2];
      }
      return id;
    }
  },
  methods: {
    handleChange() {
      if (this.selectedCateArr.length !== 3) {
        this.selectedCateArr = [];
        this.$message.warning("第三级分类才能设置参数");
        this.disabled = true;
        this[this.activeName + "Attrs"] = [];
        return false;
      }
      this.disabled = false;
      this.getParamsData();
    },
    // 1获取数据
    async getData() {
      const {
        data: { data, meta }
      } = await this.$http.get(`categories`);
      if (meta.status !== 200) return this.$message.error("获取分类失败");
      this.cascaderOptions = data;
    },
    // 2 切换选项卡触发事件
    handleClick() {
      this.getParamsData();
    },
    // 3 封装事件,重新获取参数列表的信息
    async getParamsData() {
      if (!this.thirdCateId) {
        return false;
      }
      const {
        data: { data, meta }
      } = await this.$http.get(`categories/${this.thirdCateId}/attributes`, {
        params: { sel: this.activeName }
      });
      // 动态参数列表渲染时,attr_vals需要数组
      if (this.activeName === "many") {
        data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.tagVisiable = true;
          item.inputVal = "";
        });
      }
      this[this.activeName + "Attrs"] = data;
    },
    // 4 点击添加参数，打开弹出框
    openAddDialog() {
      this.adddialogFormVisible = true;
      this.nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    // 5 点击确定,进行添加操作
    addParams() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const {
            data: { meta }
          } = await this.$http.post(
            `categories/${this.thirdCateId}/attributes`,
            {
              attr_name: this.form.attr_name,
              attr_sel: this.activeName
            }
          );
          if (meta.status !== 201) return this.$message.error("添加参数失败");
          this.$message.success("添加参数成功");
          this.adddialogFormVisible = false;
          this.getParamsData();
        }
      });
    },
    // 6 删除参数[包括静态和动态]
    delParams(attrId) {
      this.$confirm("确定删除该参数吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const {
            data: { meta }
          } = await this.$http.delete(
            `categories/${this.thirdCateId}/attributes/${attrId}`
          );
          if (meta.status !== 200) return this.$message.error("删除参数失败");
          this.getParamsData();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 7 打开编辑的弹出框
    openEditDialog(row) {
      this.editdialogFormVisible = true;
      console.log(row);
      this.$nextTick(() => {
        this.$refs.editForm.resetFields();
        this.editForm.attr_name = row.attr_name;
        this.editForm.attr_id = row.attr_id;
      });
    },
    // 7 编辑参数[包括静态和动态]
    editParams() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          const {
            data: { meta }
          } = await this.$http.put(
            `categories/${this.thirdCateId}/attributes/${
              this.editForm.attr_id
            }`,
            { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
          );
          if (meta.status !== 200) return this.$message.error("编辑参数失败");
          this.$message.success("编辑参数成功");
          this.getParamsData();
          this.editdialogFormVisible = false;
        }
      });
    },
    // 编辑参数的属性值[包括静态和动态]
    // 点击+添加tag按钮 获取焦点
    addTag(row) {
      row.tagVisiable = false;
      row.inputVal = "";
      this.$nextTick(() => {
        
        this.$refs[`add_input_${row.attr_id}`].focus();
      });
    },
    // 封装一个函数,用来删除和添加分类属性
    async editAttrVals(row) {
      const { data: {meta } }= await this.$http.put(
        `categories/${this.thirdCateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if(meta.status !==200) return this.$message.error('更新参数失败');
      this.$message.success("更新参数成功");
    },
    // 添加属性的值
    addAttrVals(row) {
      row.tagVisiable = true;
      if (!row.inputVal) return false;
      row.attr_vals.push(row.inputVal);
      this.editAttrVals(row);
    },
    // 删除属性值
    delAttrVals(row, index) {
      row.attr_vals.splice(index, 1);
      this.editAttrVals(row);
    }
  }
};
